<?php 
add_action( 'after_setup_theme', 'kawaii_setup' );
if( ! function_exists( 'kawaii_setup' ) ) :
/**
 * Init Kawaii theme
 */
function kawaii_setup() {
    // register top menu
    register_nav_menu( 'top-menu', __( 'Top Menu', 'kawaii' ) );
    
    // Require functions
    require_once( dirname(__FILE__) . '/includes/jigoshop_template_functions_override.php' );
    
    add_action('wp_enqueue_scripts', 'kawaii_scripts');
    do_action('customize_sort_action');
}
endif;


if ( ! function_exists( 'kawaii_scripts' ) ) :
/**
 * Register javascript files used in Kawaii
 */
function kawaii_scripts() {
    // register script
    wp_register_script( 'single-product', get_template_directory_uri() . '/js/single.js' );
    wp_register_script( 'customize-sort', get_template_directory_uri() . '/js/customize-sort.js' );
    wp_register_script( 'html5', get_template_directory_uri() . '/js/html5.js' );

	wp_register_script( 'kwicks', get_template_directory_uri() . '/js/jquery.kwicks-1.5.1.js', array( 'jquery' ) );
	wp_register_script ( 'home', get_template_directory_uri() . '/js/home.js', array( 'kwicks' ) );
	
    wp_register_script( 'sharethis', 'http://w.sharethis.com/button/buttons.js' );
    wp_register_script( 'carouFredSel', get_template_directory_uri() . '/js/jquery.carouFredSel-5.6.2.js' );
    wp_register_script( 'brand-slider', get_template_directory_uri() . '/js/brand-slider.js', array( 'carouFredSel' ) );

    // add scripts to all page
    wp_enqueue_script( 'html5' );
    wp_enqueue_script( 'customize-sort' );
    wp_enqueue_script( 'brand-slider' );

	if ( is_home() ) {
		wp_enqueue_script( 'home' );
	}

    // add script in single page
    if ( is_single() ) {
        wp_enqueue_script('single-product');
        wp_enqueue_script('sharethis');
    }
}
endif;

if( ! function_exists( 'kawaii_widgets_init' ) ) :
/**
 * Register widgetized areas, including two sidebars and four widget-ready columns in the footer.
 *
 * To override kawaii_widgets_init() in a child theme, remove the action hook and add your own
 * function tied to the init hook.
 *
 * @since Kawaii 1.0
 * @uses register_sidebar
 */
function kawaii_widgets_init() {

    register_sidebar( array(
            'name' => __( 'Left Sidebar Area', 'kawaii' ),
            'id' => 'left-sidebar-area',
            'description' => __( 'The Left Sidebar Area', 'kawaii' ),
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget' => '</aside>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
    ) );

    register_sidebar( array(
            'name' => __( 'Home Widget Area', 'kawaii' ),
            'id' => 'home-widget-area',
            'description' => __( 'The Widget Area on homepage', 'kawaii' ),
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget' => '</section>',
            'before_title' => '<h3 class="widget-title">',
            'after_title' => '</h3>',
    ) );
    
    add_action( 'wp_enqueue_scripts', 'kawaii_scripts' );
}
endif;
add_action( 'widgets_init', 'kawaii_widgets_init' );


function jigoshop_product_dropdown_categories_customize($hierarchal = true ) {
	global $wp_query;

	$r = array();
	$r['pad_counts'] = 1;
	$r['hierarchal'] = $hierarchal;
	$r['hide_empty'] = 0;
	$r['show_count'] = 0;
	$r['selected']   = (isset($wp_query->query['product_cat'])) ? $wp_query->query['product_cat'] : '';

	$terms = get_terms( 'product_cat', $r );
	if (!$terms) return;

	$output  = "<select name='product_cat' id='jigoshop_product_cat'>";
	//$output .= '<option value="all">'.esc_html__('Chọn danh mục', 'jigoshop').'</option>';
	$output .= jigoshop_walk_category_dropdown_tree( $terms, 0, $r );
	$output .="</select>";

        $form = '<form name="searchCustomizeForm" method="get" id="searchform" action="' . get_option('home') . '/" >
                    <div>
                        <input type="text" value="' . attribute_escape(apply_filters('the_search_query', get_search_query())) . '" name="s" id="s" placeholder="' . __( 'Product name', 'jigoshop') . '" />
                        '.$output.'
                        <input type="submit" id="searchsubmit" value="Tìm kiếm" class="button"/>
                    </div>
                </form>';
	return $form;
}

if ( ! function_exists( 'kawaii_add_vnd_currency' ) ) :
/**
 * Add VND to jigoshop plugin
 */
function kawaii_add_vnd_currency($currencies) {
    $currencies['VNĐ'] = __('Việt Nam Đồng VNĐ', 'jigoshop');
    return $currencies;
}
endif;
add_filter('jigoshop_currencies', 'kawaii_add_vnd_currency');



if ( ! function_exists( 'kawaii_add_vnd_currency_symbol' ) ) :
/**
 * Add VND symbol to jigoshop plugin
 */
function kawaii_add_vnd_currency_symbol($currency_symbol, $currency) {
    if ($currency == 'VNĐ') {
        return '<sup>đ</sup>';
    }
    return $currency_symbol;
}
endif;
add_filter('jigoshop_currency_symbol', 'kawaii_add_vnd_currency_symbol', 1 ,2);


if ( ! function_exists( 'kawaii_custom_menu' ) ) :
/**
 * Customize Billing Fields in checkout page
 */
function kawaii_custom_billing_fields( $fields ) {
    unset( $fields[2], $fields[6], $fields[7], $fields[8] );
    return $fields;
}
endif;
add_filter( 'jigoshop_billing_fields', 'kawaii_custom_billing_fields' );


if ( ! function_exists( 'kawaii_comments' ) ) :
/**
 * Print out user comments
 */
function kawaii_comments($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment; global $post; ?>

	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
		<div id="comment-<?php comment_ID(); ?>" class="comment_container">

  			<?php echo get_avatar( $comment, $size='60' ); ?>

			<div class="comment-text-wrapper">
			     <div class="comment-text">
				<?php if ( $rating = get_comment_meta( $comment->comment_ID, 'rating', true ) ): ?>
				<div class="star-rating" title="<?php echo esc_attr( $rating ); ?>">
					<span style="width:<?php echo $rating*16; ?>px"><?php echo $rating; ?> <?php _e('out of 5', 'jigoshop'); ?></span>
				</div>
				<?php endif; ?>
				<?php if ($comment->comment_approved == '0') : ?>
					<p class="meta"><em><?php _e('Your comment is awaiting approval','jigoshop'); ?></em></p>
				<?php else : ?>
					<p class="meta">
						<?php _e('Rating by','jigoshop'); ?> <strong class="reviewer vcard"><span class="fn"><?php comment_author(); ?></span></strong> <?php _e('on','jigoshop'); ?> <?php echo date_i18n(get_option('date_format'), strtotime(get_comment_date('Y-m-d'))); ?>:
					</p>
				<?php endif; ?>
  				<div class="description"><?php comment_text(); ?></div>
  				<div class="clear"></div>
  				</div>
  			</div>
			<div class="clear"></div>
		</div>
	<?php
}
endif;


/**
 * Return initial brand menu items with minimal inforamtion to be able to display in top menu
 */
function kawaii_get_product_brands() {

    $terms = get_terms( 'product_tag', array( 'hide_empty' => '0' ) );
    $menu_items = array();

    foreach ( $terms as $t ) {
        unset ($menu_item);
        $menu_item->type = 'taxonomy';
        $menu_item->url = $t->slug;
        $menu_item->title = $t->name;
        $menu_item->object = 'product_tag';

        $menu_items[] = $menu_item;
    }
    return $menu_items;
}

add_action( 'customize_sort_action', 'customize_sort' );
function customize_sort() {
    if ($_GET["orderby"] == "price") {
        add_filter('posts_where', 'edit_posts_where_price');
        add_filter('posts_orderby', 'edit_posts_orderby_price');
    } else if ($_GET["orderby"] == 'rating') {
        add_filter('posts_orderby', 'edit_posts_orderby_rating');
    }
}

function edit_posts_where_price($where) {
	$where .= " AND p3.post_type = 'product_variation' ";
        $where .= " AND mt1.meta_key = 'regular_price' ";
	return $where;
}

function edit_posts_orderby_price($orderby) {
	$orderby = " mt1.meta_value+0 " . $_GET["order"];
	return $orderby;
}

function edit_posts_orderby_rating($orderby) {
	$orderby = " wp_commentmeta.meta_value+0 " . $_GET["order"];
	return $orderby;
}

function join_MORE_TABLE_to_WPQuery_to_SORT_RATING($join) {
    global $wpdb;
    $join .= " LEFT JOIN $wpdb->comments ON $wpdb->posts.ID = $wpdb->comments.comment_post_id ";
    $join .= " LEFT JOIN $wpdb->commentmeta ON $wpdb->comments.comment_id = $wpdb->commentmeta.comment_id ";
    return $join;
}

function join_MORE_TABLE_to_WPQuery_to_SORT_PRICE($join) {
    global $wpdb;
    $join .= " LEFT JOIN $wpdb->posts AS p3 ON p3.post_parent = $wpdb->posts.ID ";
    $join .= " INNER JOIN $wpdb->postmeta AS mt1 ON p3.ID = mt1.post_id ";
    return $join;
}

if ($_GET["orderby"] == 'rating') {
    add_filter('posts_join', 'join_MORE_TABLE_to_WPQuery_to_SORT_RATING');
} else if ($_GET["orderby"] == 'price') {
    add_filter('posts_join', 'join_MORE_TABLE_to_WPQuery_to_SORT_PRICE');
}

class Walker_Nav_Menu_Dropdown extends Walker_Nav_Menu {
    function start_lvl(&$output, $depth){
        $indent = str_repeat("\t", $depth); // don't output children opening tag (`<ul>`)
    }

    function end_lvl(&$output, $depth){
        $indent = str_repeat("\t", $depth); // don't output children closing tag
    }

    function start_el(&$output, $item, $depth, $args){

        global $wp_query;
		$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

		$class_names = $value = '';

		$classes = empty( $item->classes ) ? array() : (array) $item->classes;
		$classes[] = 'menu-item-' . $item->ID;

		$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
		$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

		$id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
		$id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

		$output .= $indent . '<option' . $id . $value . $class_names .' value="' . esc_attr( $item->url        ) . '">';

		$attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
		$attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
		$attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
		$attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

		$item_output = $args->before;
		$item_output .= $args->link_before . apply_filters( 'the_title', str_repeat("&nbsp;", $depth * 4).$item->title, $item->ID ) . $args->link_after;
		$item_output .= $args->after;

		$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );

    }

    function end_el(&$output, $item, $depth){
      $output .= "</option>\n"; // replace closing </li> with the option tag
    }
}

remove_action('order_status_pending_to_processing', 'jigoshop_new_order_notification');
remove_action('order_status_pending_to_completed', 'jigoshop_new_order_notification');
remove_action('order_status_pending_to_on-hold', 'jigoshop_new_order_notification');
remove_action('order_status_pending_to_processing', 'jigoshop_processing_order_customer_notification');
remove_action('order_status_pending_to_on-hold', 'jigoshop_processing_order_customer_notification');
remove_action('order_status_completed', 'jigoshop_completed_order_customer_notification');
remove_action('order_status_refunded', 'jigoshop_refunded_order_customer_notification');

add_action('order_status_pending_to_processing', 'jigoshop_new_order_notification_customize');
add_action('order_status_pending_to_completed', 'jigoshop_new_order_notification_customize');
add_action('order_status_pending_to_on-hold', 'jigoshop_new_order_notification_customize');
add_action('order_status_pending_to_processing', 'jigoshop_processing_order_customer_notification_customize');
add_action('order_status_pending_to_on-hold', 'jigoshop_processing_order_customer_notification_customize');
add_action('order_status_completed', 'jigoshop_completed_order_customer_notification_customize');
add_action('order_status_refunded', 'jigoshop_refunded_order_customer_notification_customize');

function jigoshop_new_order_notification_customize($order_id) {
    $order = new jigoshop_order($order_id);
    $subject = sprintf(__('[%s] Đơn Hàng Mới (MÃ: %s)', 'jigoshop'), get_bloginfo('name'), $order->id);
    
    ob_start();

    echo __("Bạn nhận được 1 đơn hàng từ ", 'jigoshop') . $order->billing_first_name . ' ' . $order->billing_last_name 
         . __(". Đơn hàng như sau: ", 'jigoshop') . PHP_EOL . PHP_EOL;
    add_header_info_customize($order);
    add_order_totals_customize($order, false, true);
    add_customer_details_customize($order);

    add_billing_address_details_customize($order);
    add_shipping_address_details_customize($order);

    $message = ob_get_clean();
    $message = apply_filters('jigoshop_change_new_order_email_contents', $message, $order);
    $message = html_entity_decode(strip_tags($message));

    wp_mail(get_option('jigoshop_email'), $subject, $message, "Từ: " . get_option('jigoshop_email') . "\r\n");
}

function jigoshop_processing_order_customer_notification_customize($order_id) {
    $order = new jigoshop_order($order_id);
    $subject = '[' . get_bloginfo('name') . '] ' . __('Kawaii Shop đã nhận đơn hàng', 'jigoshop');
    ob_start();
    
    echo PHP_EOL . __("Cảm ơn vì đã chọn Kawaii Shop. Chúng tôi đang đã nhận được đơn hàng của bạn như bên dưới: ", 'jigoshop') . PHP_EOL . PHP_EOL;
    add_header_info_customize($order);
    add_order_totals_customize($order, false, true);
    if (strtolower($order->payment_method) == "bank_transfer") :
        echo __('THÔNG TIN THANH TOÁN QUA NGÂN HÀNG', 'jigoshop') . PHP_EOL;
        echo $order->email_bank_details();
        echo PHP_EOL;
        do_action('jigoshop_after_email_bank_payment_details', $order->id);
    endif;

    add_customer_details_customize($order);
    add_billing_address_details_customize($order);
    add_shipping_address_details_customize($order);
    $message = ob_get_clean();
    $message = apply_filters('jigoshop_change_processing_order_email_contents', $message, $order);
    $message = html_entity_decode(strip_tags($message));

    wp_mail($order->billing_email, $subject, $message, "Từ: " . get_option('jigoshop_email') . "\r\n");
}

function jigoshop_completed_order_customer_notification_customize($order_id) {
    $order = new jigoshop_order($order_id);
    $subject = '[' . get_bloginfo('name') . '] ' . __('Đặt hàng thành công', 'jigoshop');

    ob_start();
    echo __("Đơn hàng của bạn đã hoàn tất. Chi tiết như sau: ", 'jigoshop') . PHP_EOL . PHP_EOL;

    add_header_info_customize($order);
    add_order_totals_customize($order, true, true);
    add_customer_details_customize($order);
    add_billing_address_details_customize($order);
    add_shipping_address_details_customize($order);

    $message = ob_get_clean();
    $message = apply_filters('jigoshop_change_completed_order_email_contents', $message, $order);
    $message = html_entity_decode(strip_tags($message));
    $message = apply_filters('jigoshop_completed_order_customer_notification_mail_message', $message);
    
    wp_mail($order->billing_email, $subject, $message, "Từ: " . get_option('jigoshop_email') . "\r\n");
}

function jigoshop_refunded_order_customer_notification_customize($order_id) {

    $order = new jigoshop_order($order_id);

    $subject = '[' . get_bloginfo('name') . '] ' . __('Đặt hàng thất bại', 'jigoshop');

    ob_start();
    echo __("Đơn hàng của bạn đã được trả lại. Chi tiết như sau: ", 'jigoshop') . PHP_EOL . PHP_EOL;

    add_header_info_customize($order);
    add_order_totals_customize($order, false, true);
    add_customer_details_customize($order);
    add_billing_address_details_customize($order);
    add_shipping_address_details_customize($order);

    $message = ob_get_clean();
    $message = apply_filters('jigoshop_change_refunded_email_message', $message, $order);
    $message = html_entity_decode(strip_tags($message));
    $message = apply_filters('jigoshop_refunded_order_customer_notification_mail_message', $message);

    wp_mail($order->billing_email, $subject, $message, "Từ: " . get_option('jigoshop_email') . "\r\n");
}

function add_header_info_customize($order) {
    add_company_information_customize();
    echo __('MÃ ĐƠN HÀNG: ', 'jigoshop') . $order->id . "\t\t" 
         . ' Mua lúc: ' . date_i18n(get_option('time_format'), strtotime($order->order_date)) . ' '
         . date_i18n(get_option('date_format'), strtotime($order->order_date)) . PHP_EOL . PHP_EOL;
}

function add_order_totals_customize($order, $show_download_links, $show_sku) {
    echo $order->email_order_items_list($show_download_links, $show_sku);

    if ($order->customer_note) :
        echo PHP_EOL . __('Ghi chú: ', 'jigoshop') . "\t\t " . $order->customer_note . PHP_EOL;
    endif;

    if ((get_option('jigoshop_calc_taxes') == 'yes' && $order->has_compound_tax())
        || (get_option('jigoshop_tax_after_coupon') == 'yes' && $order->order_discount > 0))
        echo PHP_EOL . __('Giá bán lẻ: ', 'jigoshop') . "\t\t" . html_entity_decode($order->get_subtotal_to_display(), ENT_COMPAT, 'UTF-8') . PHP_EOL;
    
    if ($order->order_shipping > 0)
        echo __('Phí vận chuyển: ', 'jigoshop') . "\t\t" . html_entity_decode($order->get_shipping_to_display(), ENT_COMPAT, 'UTF-8') . PHP_EOL;
    
    if (get_option('jigoshop_tax_after_coupon') == 'yes' && $order->order_discount > 0)
        echo __('Giảm giá: ', 'jigoshop') . "\t\t" . html_entity_decode(jigoshop_price($order->order_discount), ENT_COMPAT, 'UTF-8') . PHP_EOL;
    
    if ((get_option('jigoshop_calc_taxes') == 'yes' && $order->has_compound_tax())
        || (get_option('jigoshop_tax_after_coupon') == 'yes' && $order->order_discount > 0))
        echo __('Subtotal:', 'jigoshop') . "\t\t" . html_entity_decode(jigoshop_price($order->order_discount_subtotal), ENT_COMPAT, 'UTF-8') . PHP_EOL;
    
    if (get_option('jigoshop_calc_taxes') == 'yes') :
        foreach ($order->get_tax_classes() as $tax_class) :
            if ($order->show_tax_entry($tax_class))
                echo $order->get_tax_class_for_display($tax_class) . ' (' . (float) $order->get_tax_rate($tax_class) . '%):' . "\t\t\t" . html_entity_decode($order->get_tax_amount($tax_class), ENT_COMPAT, 'UTF-8') . PHP_EOL;
        endforeach;
    endif;
    
    if (get_option('jigoshop_tax_after_coupon') == 'no' && $order->order_discount > 0)
        echo __('Giảm giá: ', 'jigoshop') . "\t\t" . html_entity_decode(jigoshop_price($order->order_discount), ENT_COMPAT, 'UTF-8') . PHP_EOL;
    echo __('Tổng cộng: ', 'jigoshop') . "\t\t" . html_entity_decode(jigoshop_price($order->order_total), ENT_COMPAT, 'UTF-8') . PHP_EOL . PHP_EOL;

    if (get_option('jigoshop_calc_taxes') && get_option('jigoshop_tax_number')) :
        echo get_option('jigoshop_tax_number') . PHP_EOL . PHP_EOL;
    endif;

    do_action('jigoshop_after_email_order_info', $order->id);
}

function add_customer_details_customize($order) {
    echo __('THÔNG TIN KHÁCH HÀNG', 'jigoshop') . PHP_EOL;

    if ($order->billing_email)
        echo __('Email: ', 'jigoshop') . "\t\t\t " . $order->billing_email . PHP_EOL;
    if ($order->billing_phone)
        echo __('Điện thoại: ', 'jigoshop') . "\t\t" . $order->billing_phone . PHP_EOL;

    echo PHP_EOL;
    do_action('jigoshop_after_email_customer_details', $order->id);
}

function add_billing_address_details_customize($order) {
    echo __('ĐỊA CHỈ THANH TOÁN: ', 'jigoshop') . PHP_EOL;

    echo $order->billing_first_name . ' ' . $order->billing_last_name . PHP_EOL;
    if ($order->billing_company)
        echo $order->billing_company . PHP_EOL;
    echo $order->formatted_billing_address . PHP_EOL . PHP_EOL;

    do_action('jigoshop_after_email_billing_address', $order->id);
}

function add_shipping_address_details_customize($order) {
    if ($order->shipping_first_name != '') {
        echo __('ĐỊA CHỈ GIAO HÀNG: ', 'jigoshop') . PHP_EOL;
        echo $order->shipping_first_name . ' ' . $order->shipping_last_name . PHP_EOL;
        if ($order->shipping_company)
            echo $order->shipping_company . PHP_EOL;
        echo $order->formatted_shipping_address . PHP_EOL . PHP_EOL;

        do_action('jigoshop_after_email_shipping_address', $order->id);
    }
}

function add_company_information_customize() {
    $add_eol = false;
    
    if (get_option('jigoshop_company_name')) :
        echo "\t\t\t\t\t\t" . get_option('jigoshop_company_name') . PHP_EOL;
        $add_eol = true;
    endif;
    
    if (get_option('jigoshop_address_line1')) :
        $add_eol = true;
        echo "\t\t\t\t\t\t" . get_option('jigoshop_address_line1') . PHP_EOL;
        if (get_option('jigoshop_address_line2')) :
            echo "\t\t\t\t\t\t" . get_option('jigoshop_address_line2') . PHP_EOL;
        endif;
    endif;
    
    if (get_option('jigoshop_company_phone')) :
        $add_eol = true;
        echo "\t\t\t\t\t\t" . get_option('jigoshop_company_phone') . PHP_EOL;
    endif;
    
    if (get_option('jigoshop_company_email')) :
        $add_eol = true;
        echo "\t\t\t\t\t\t" . '<a href="mailto:' . get_option('jigoshop_company_email') . '">' . get_option('jigoshop_company_email') . '</a>' . PHP_EOL;
    endif;
    
    if ($add_eol) echo PHP_EOL;
    
}

?>